import socket

def send_message(udp_socket):
    msg = input('请输入你要发送的信息：')
    dest_ip = input('请输入对方IP地址：')
    try:
        dest_port = int(input('请输入对方端口：'))
        udp_socket.sendto(msg.encode('utf-8'),(dest_ip, dest_port))
    except Exception as e:
        print('输入信息有误，请重新输入 %s' % e)

def recv_message(udp_socket):
    recv_msg = udp_socket.recvfrom(1024)
    recv_ip_port = recv_msg[1]
    recv_msg = recv_msg[0].decode('utf-8')
    print(f'消息内容：{recv_msg}。发送方的IP和端口{recv_ip_port}')

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    # 绑定本机端口
    udp_socket.bind(('', 9999))

    while True:
        print('='*30)
        print('1、发送消息')
        print('2、接收消息')
        print('='*30)

        num = int(input('请输入你要序号：'))

        if num == 1:
            # print('发送')
            send_message(udp_socket)
        elif num == 2:
            # print('接收')
            recv_message(udp_socket)
        else:
            print('输入有误，请重新输入：')

if __name__ == '__main__':
    main()